import { Mesh, BufferGeometry, MeshBasicMaterial, DoubleSide, LineSegments, LineBasicMaterial, Object3D } from "three";
import vjmap from "vjmap";
import { App, MiniMapControl, PathAnimateModule, ResManager, approxArrayEquals, disposeObject3D, fromWorld, loadPluginAlgorithm } from "vjmap3d";
import { showMessageTip } from "./ui";

let tempId = vjmap.getTempMapId()
let isWorking = false
// 根据模型导出二维cad平面图
export const exportModelToDwg = async (app: App, model: Object3D, addEntities?: any[]) => {
    if (isWorking) {
        showMessageTip(app, "正忙,请稍候重试...")
        return;
    }
    isWorking = true;
    let entitys: any = addEntities ?? [];
    if (model.children.length > 0) {
        let amLib = await loadPluginAlgorithm();
        let silhouette = new Mesh(
            new BufferGeometry(),
            new MeshBasicMaterial({
                color: "#eee",
                side: DoubleSide
            })
        );
        let outlines = new LineSegments(
            new BufferGeometry(),
            new LineBasicMaterial({ color: 0x030303 })
        );
        let opModel = model;
        if (app.isMapMode) {
            // 因为地图模式下，y轴往上，要旋转下
            opModel = opModel.clone();
            opModel.rotateX(-Math.PI / 2)
        }
        // 如果要查看实时生成的，可用下面的
        //app.scene.add(outlines, silhouette);
        let task = amLib.createProjectionTask({
            model: opModel,
            silhouette,
            outlines,
            //updateProgressCb: (name, progress) => console.log(name, progress),
            updateVisible: undefined,
            ANGLE_THRESHOLD: 50
        });
        await task.promise();
        
        let positions = outlines.geometry.attributes.position.array;
       
        for (let n = 0; n < positions.length; n += 6) {
            // 如果是地图模式，yz要互换下， z轴方向坐标还要取反下
            let start = fromWorld([positions[n], app.isMapMode? -positions[n + 2] : positions[n + 1], app.isMapMode? positions[n + 1] :positions[n + 2]]);
            let end = fromWorld([positions[n + 3], app.isMapMode? -positions[n + 5] : positions[n + 4], app.isMapMode? positions[n + 4] : positions[n + 5]])
            if (approxArrayEquals(start, end)) continue; // 两点重合
            entitys.push({
                typename: "DbLine",
                start: start,
                end: end
            });
        }
        if (app.isMapMode) {
            // 把临时创建的删除了
            disposeObject3D(opModel)
        }
    }
   
    let doc = {
        entitys
    };

    let res = await app.svc.updateMap({
        mapid: tempId,
        filedoc: JSON.stringify(doc),
        mapopenway: vjmap.MapOpenWay.Memory,
        style: {
            backcolor: 0 // 如果div背景色是浅色，则设置为oxFFFFFF
        }
    });
    let href = `${app.svc.baseUrl()}_cloud/#/map/${res.mapid}?version=${
        res.version
    }&mapopenway=Memory&vector=false&isFitMap=true`;
    window.open(href);
    isWorking = false;
};


export const createRoutePath = async (app: App, modelSize: number) => {
    let line = await app.actionDrawLineSting({
        isAddToApp: true
    });
    if (line.isCancel) return
    // 获取最后加的数据,用于线路结束后删除
    let data = app.getDrawLayer().polylines()?.getData();
    // @ts-ignore
    let lineData = data[data?.length - 1]
    
    let ent = await ResManager.loadModel("./models/soldier.glb", {
        size: modelSize,
        splitSubEntity: true
    });
    ent.addTo(app);
    
    let miniMapControl;
    if (!app.isMapMode) {
        // 纯三维模式下显示小地图
        miniMapControl = new MiniMapControl({
            followTarget: ent.node,
           // mapSyncRotateZ: true,
            mapSize: 10,
        });
        app.addControl(miniMapControl)
    }
   
    

    let pathAnmiMod = ent.add(PathAnimateModule)
    await pathAnmiMod.start({
        paths: line.data.coordinates,
        cameraFollow: true, 
       // followDist: fromDist(followDist),
       // followDist: app.isMapMode ? 23327: undefined,
       // offsetAngle:90,
        //followAngle: 15,
        animation: {
            duration: 10000
        },
        startAimatorClipName: 'Walk',
        stopAimatorClipName: ""
    })

    if (miniMapControl) {
        app.removeControl(miniMapControl);
    }
    // 移除实体
    ent.remove()
    // 移除路径线
    app.getDrawLayer().deletePolylineData(lineData);
}